<template>
  <div>
    <div class="w-100 flex" style="height:97.9%">
      <div class="h-100 flex-column justify-between" style="width:25%">
        <div data-bottom class="h-33">
          <page-header text="农产品种植情况" :ph="215">
            <v-chart
              ref="ncpzz"
              :theme="theme"
              :is-show="tortadiagram.isShow"
              :options="tortadiagram"
            /></page-header>
        </div>
        <div data-bottom class="h-33">
          <page-header text="农产品产量" :ph="215"> <v-chart v-if="pies.isShow" ref="ncpcl" :theme="theme" :options="pies" /></page-header>
        </div>
        <div data-bottom class="h-33">
          <page-header text="主要农产品单位面积产量" :ph="215">
            <v-chart v-if="category2.isShow" ref="zyncpdwmjcl" :theme="theme" :options="category2" />
          </page-header>
        </div>
      </div>
      <div style="width:1%" />
      <div class="h-100 map-box" data-bottom style="width:48%;height:100%; padding: 2px;">
        <div class="map-type">
          <div class="item-map-type" :class="{ active: index == '0' }" @click="tabType('0')">种植面积</div>
          <div class="item-map-type" :class="{ active: index == '1' }" @click="tabType('1')">受灾成灾</div>
          <div class="item-map-type" :class="{ active: index == '2' }" @click="tabType('2')">经营主体分布</div>
        </div>
        <div v-if="index == '0'" class="position-relative" style="height: 100%;">
          <div id="container" style="height: 100%;background:none; " />
          <div class="map-legend-bar">
            <div v-for="item in colorList" :key="item.color" class="flex map-legend-bar-item">
              <div class="map-legend-bar-color" :style="{ background: item.color }" />
              <div class="">{{ item.name }}</div>
            </div>
          </div>
        </div>
        <div v-if="index == '1'" id="heatMap" style="height: 100%" />
        <div v-if="index == '2'" class="position-relative" style="height: 100%;">
          <div id="businessEntity" style="height: 100%" />
          <div class="map-legend">
            <div v-for="item in imgList" :key="item.color" class="flex map-legend-item">
              <div class="map-legend-color">
                <img :src="item.url" alt="">
              </div>
              <div class="">{{ item.type }}</div>
            </div>
          </div>
        </div>
      </div>
      <div style="width:1%" />
      <div class="h-100 flex-column justify-between" style="width:25%">
        <div data-bottom class="h-33">
          <page-header
            text="新型经营主体经营情况"
            :ph="215"
          ><v-chart
            v-if="optionXjyzt.isShow"
            ref="xxjyztjyqk"
            :theme="theme"
            :options="optionXjyzt"
          /></page-header>
        </div>
        <div data-bottom class="h-33">
          <page-header text="主要畜牧产量" :ph="215">
            <v-chart v-if="columnar.isShow" ref="zyxmcl" :theme="theme" :options="columnar" />
          </page-header>
        </div>
        <div data-bottom class="h-33">
          <page-header text="受灾和成灾面积" :ph="215"> <v-chart :theme="theme" :options="pie" /></page-header>
        </div>
      </div>
    </div>
    <div style="height:2.1%" />
    <Particulars />
  </div>
</template>

<script>
import AMap from '@/utils/AMap'
import Particulars from 'header/particulars.vue'
import PageHeader from 'header/PageHeader.vue'
import theme from '@/utils/echarts-theme.json'
import echarts from 'echarts'
import { formatNumber } from '@/utils/app'
import { twoPieChartValue, getSingleValue, plantAreaCrops, disasterArea, produceBusiness, getTowSideStat } from '@/api/connector'

export default {
  name: 'IndustrialBase',
  components: {
    // eslint-disable-next-line vue/no-unused-components
    PageHeader,
    Particulars
  },
  data() {
    return {
      index: 0,
      theme: theme,
      map: null,
      mapType: '',
      amap: '',
      infoWindow: null,
      p1: null,
      p2: null,
      time: null,
      showIndex: 0,
      mapData: [],
      starCenter: [108.207004, 34.236131],
      path: [],
      heatMap: null,
      businessEntityMap: null,
      colorList: [
        {
          type: '1',
          name: '农作物总播种面积',
          color: '#2DAFFF'
        },
        {
          type: '2',
          name: '粮食作物播种面积',
          color: '#6141FF'
        },
        {
          type: '3',
          name: '主要农产品播种面积',
          color: '#15F0C0'
        },
        {
          type: '4',
          name: '其他',
          color: '#F3F81A'
        }
      ],
      imgList: [
        {
          url: require('./../../../assets/img/map/1.png'),
          type: '农资'
        },
        {
          url: require('./../../../assets/img/map/2.png'),
          type: '农机'
        },
        {
          url: require('./../../../assets/img/map/3.png'),
          type: '加工'
        },
        {
          url: require('./../../../assets/img/map/4.png'),
          type: '仓储'
        },
        {
          url: require('./../../../assets/img/map/5.png'),
          type: '物流'
        },
        {
          url: require('./../../../assets/img/map/6.png'),
          type: '家庭农场'
        },
        {
          url: require('./../../../assets/img/map/7.png'),
          type: '合作社'
        },
        {
          url: require('./../../../assets/img/map/8.png'),
          type: '现代产业园'
        },
        {
          url: require('./../../../assets/img/map/9.png'),
          type: '农科企业'
        }
      ],
      columnar: {
        isShow: false,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          // formatter: '{b}<br />{a2}:{c2}%<br />{a1}:{c1}%<br />{a0}:{c0}%'
          formatter: function(params, ticket, callback) {
            var htmlStr = ''
            for (var i = 0; i < params.length; i++) {
              var param = params[i]
              var xName = param.name // x轴的名称
              var seriesName = param.seriesName // 图例名称
              var value = param.value // y轴值
              var color = param.color // 图例颜色
              if (i === 0) {
                htmlStr += xName + '<br/>' // x轴的名称
              }
              htmlStr += '<div>'
              htmlStr +=
                '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' + color + ';"></span>' // 一个点
              htmlStr += seriesName + '：' + formatNumber(value) + '头' // 圆点后面显示的文本
              htmlStr += '</div>'
            }
            return htmlStr
          }
        },
        legend: {
          data: []
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            axisLine: {
              lineStyle: {
                color: '#E9F7FF',
                width: 1
              }
            },
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '头',
            axisLine: {
              lineStyle: {
                color: '#E9F7FF',
                width: 1
              }
            },
          }
        ],
        series: [
          {
            name: '直接访问',
            type: 'bar',
            stack: '广告',
            data: [320, 332, 301, 334, 390, 330, 320]
          },
          {
            name: '邮件营销',
            type: 'bar',
            stack: '广告',
            data: [120, 132, 101, 134, 90, 230, 210]
          },
          {
            name: '联盟广告',
            type: 'bar',
            stack: '广告',
            data: [220, 182, 191, 234, 290, 330, 310]
          }
        ]
      },
      tortadiagram: {
        isShow: false,
        // title: {
        //   text: '',
        //   x: 'center',
        //   y: '45%',
        //   textStyle: {
        //     fontSize: 14
        //   }
        // },
        title:[
          {
            text: '',
            left: 'center',
            top: '45%',
            textStyle: {
              color: '#fff',
              fontSize: 14
            }
          },
          {
            id: 'statistic',
            text: "亩",
            left: 'center',
            top: '55%',
            textStyle: {
              color: '#fff',
              fontSize: 14
            }
          }
        ],
        tooltip: {
          trigger: 'item',
          // formatter: '{b}: {c} 亩({d}%)'
          formatter:function( params ){
            var  result = '';
            return result=params.marker+params.name+' : '+formatNumber(params.value)+'亩  '+params.percent+' %</br>'
          }  
        },
        legend: {
          orient: 'horizontal',
          left: 10,
          data: []
        },
        series: [
          {
            name: ' ',
            type: 'pie',
            radius: ['50%', '70%'],
            center: ['50%', '55%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'bottom',
              offset: [0, 50],
              formatter: function(params) {
                // if (params.name !== '') {
                //   // return params.name + '\n' + '(' + params.percent + '%)';
                //   return formatNumber(params.value) + ' 亩'
                // } else {
                //   return ''
                // }

                return params.percent + '%';
              }
            },
            labelLine: {
              show: true
            },
            data: [
              // { value: 335, name: '直接访问' },
              // { value: 310, name: '邮件营销' },
              // { value: 234, name: '联盟广告' },
              // { value: 135, name: '视频广告' },
              // { value: 1548, name: '搜索引擎' }
            ]
          }
        ]
      },
      optionXjyzt: {
        isShow: false,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          // formatter: '{b}<br />{a2}:{c2}%<br />{a1}:{c1}%<br />{a0}:{c0}%'
          formatter: function(params, ticket, callback) {
            var htmlStr = ''
            for (var i = 0; i < params.length; i++) {
              var param = params[i]
              var xName = param.name // x轴的名称
              var seriesName = param.seriesName // 图例名称
              var value = param.value // y轴值
              var color = param.color // 图例颜色
              if (i === 0) {
                htmlStr += xName + '<br/>' // x轴的名称
              }
              htmlStr += '<div>'
              htmlStr +=
                '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' + color + ';"></span>' // 一个点
              htmlStr += seriesName + '：' + formatNumber(value) + (seriesName === '年度总收入' ? '亿元' : '吨') // 圆点后面显示的文本
              htmlStr += '</div>'
            }
            return htmlStr
          }
        },
        legend: {
          textStyle: {
            color: '#fff'
          },
          data: ['可用余额', '不可用余额', '收入', '支出']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          axisLine: {
            lineStyle: {
              color: '#E9F7FF',
              width: 1
            }
          },
          data: []
        },
        yAxis: [
          {
            name: '吨',
            axisLine: {
              lineStyle: {
                color: '#E9F7FF',
                width: 1
              }
            },
            position: 'left',
            splitLine: {
              // 分割线配置
              lineStyle: {
                color: '#AAAAAA56'
              }
            }
          },
          {
            name: '亿元',
            position: 'right',
            axisLine: {
              lineStyle: {
                color: '#E9F7FF',
                width: 1
              }
            },
          }
        ],
        series: []
      },
      pie: {
        isShow: false,
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}千公顷 ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          left: 10,
          data: [],
          textStyle: {
            color: '#fff'
          }
        },
        series: [
          {
            name: '占比',
            type: 'pie',
            selectedMode: 'single',
            radius: [0, '30%'],
            // label: {
            //   position: 'inner'
            // },
            label: {
              formatter: function(params) {
                return params.percent + '%';
              },
            },
            labelLine: {
              show: false
            },
            data: []
          },
          {
            name: '比例',
            type: 'pie',
            radius: ['40%', '55%'],
            label: {
              formatter: function(params) {
                // if (params.name !== '') {
                //   // return params.name + '\n' + '(' + params.percent + '%)';
                //   return formatNumber(params.value) + ' 千公顷'
                // } else {
                //   return ''
                // }

                return params.percent + '%';
              }
            },
            data: []
          }
        ]
      },
      pies: {
        isShow: false,
        tooltip: {
          trigger: 'item',
          // formatter: '{a} <br/>{b}: {c}吨 ({d}%)'
          formatter:function( params ){
            var  result = '';
            return result=params.marker+params.name+' : '+formatNumber(params.value)+'吨  '+params.percent+' %</br>'
          } 
        },
        legend: {
          orient: 'horizontal',
          left: 10,
          data: [],
          textStyle: {
            color: '#fff'
          }
        },
        series: [
          {
            name: '占比',
            type: 'pie',
            selectedMode: 'single',
            radius: [0, '30%'],

            // label: {
            //   position: 'inner'
            // },
            label: {
              formatter: function(params) {
                // if (params.name == '主要农作物产量') {
                //   // return params.name + '\n' + '(' + params.percent + '%)';
                //   return formatNumber(params.value) + ' 吨\n\n\n'
                // } else {
                //   return formatNumber(params.value) + ' 吨'
                // }
                if (params.name == '主要农作物产量') {
                  return ''
                } else {
                  return params.percent + '%';
                }
              }
            },
            labelLine: {
              show: false
            },
            data: []
          },
          {
            name: '比例',
            type: 'pie',
            radius: ['40%', '55%'],
            labelLine: {
              show: true,
              length: 10,
              length2: 20
            },
            label: {
              formatter: function(params) {
                // if (params.name == '主要农作物产量') {
                //   // return params.name + '\n' + '(' + params.percent + '%)';
                //   return formatNumber(params.value) + ' 吨\n\n\n'
                // } else {
                //   return formatNumber(params.value) + ' 吨'
                // }

                return params.percent + '%';
              }
            },
            data: []
          }
        ]
      },
      category2: {
        isShow: false,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          },
          formatter:function( params ){
            console.log(params)
            var  result = params[0].name+'<br>';
            params.forEach(function (item) {
                result+=item.marker+item.seriesName+' : '+item.value+' 公斤/亩</br>'
            });
            return  result;
          }
        },
        legend: {
          data: []
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            axisLine: {
              lineStyle: {
                color: '#E9F7FF',
                width: 1
              }
            },
            data: []
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '公斤/亩',
            axisLine: {
              lineStyle: {
                color: '#E9F7FF',
                width: 1
              }
            },
          }
        ],
        series: [
          {
            name: '区域值',
            type: 'line',
            areaStyle: {},
            data: [120, 132, 101, 134, 90, 230, 210]
          },
          {
            name: '国家值',
            type: 'line',
            areaStyle: {},
            data: [220, 182, 191, 234, 290, 330, 310]
          }
        ]
      }
    }
  },
  created() {
    this.init()
  },
  beforeDestroy() {
    clearTimeout(this.time)
  },
  mounted() {
    this.$nextTick(() => {
      this.farming()
    })
  },
  methods: {
    toFour(name, isCodew, typeCode) {
      if (name === isCodew) {
        this.$router.push({ name: 'Fourstage', query: { code: '000201', name: this.$route.matched[0].name, typeCode: typeCode || isCodew }})
      }
    },
    tabType(index) {
      this.index = index
      switch (index) {
        case '0':
          this.farming()
          break
        case '1':
          this.getHeatMap()
          break
        case '2':
          setTimeout(() => {
            this.businessEntity()
          }, 0)
          break
        default:
          break
      }
    },
    init() {
      //  劳动力人口情况
      twoPieChartValue({
        groupCode: 'SZQK'
      }).then((res) => {
        this.pie.legend.data = res.body.names
        this.pie.series[0].data = res.body.values.out
        this.pie.series[1].data = res.body.values.inner
        this.isShow1 = true
      })
      // 主要农产品单位面积产量
      getTowSideStat({ groupCode: 'ZYNCPDWMJCL' }).then((res) => {
        const val = res.body
        const category2 = this.category2
        category2.xAxis[0].data = val.dateSet
        category2.legend.data = val.typeSet
        Object.keys(val.typeValueListMap).forEach((k, i) => {
          category2.series[i].data = val.typeValueListMap[(category2.series[i].name = k)]
        })
        category2.isShow = true
        this.toLink(this, 'zyncpdwmjcl', (p) => {
          console.log(p)
          this.toFour(p.name, '主要农作物单位面积产量')
        })
      })
      // 主要畜牧产量
      getTowSideStat({ groupCode: 'YZYGK' }).then((res) => {
        const val = res.body
        const columnar = this.columnar
        columnar.legend.data = val.typeSet
        columnar.xAxis[0].data = val.dateSet
        var obj = res.body.typeValueListMap
        var key = []
        var value = []
        for (var i in obj) {
          key.push(i)
          value.push(obj[i])
        }
        columnar.series[0].data = value[0]
        columnar.series[0].name = key[0]
        columnar.series[1].data = value[1]
        columnar.series[1].name = key[1]
        columnar.series[2].data = value[2]
        columnar.series[2].name = key[2]
        columnar.isShow = true
        this.toLink(this, 'zyxmcl', (p) => {
          this.toFour(p.seriesName, '猪年底头数')
          this.toFour(p.seriesName, '猪出栏头数', '猪出栏数量')
        })
      })
      //  新型经营主体经营情况
      getTowSideStat({ groupCode: 'XXJYZTJYQK' }).then((data) => {
        const val = data.body
        const optionXjyzt = this.optionXjyzt
        optionXjyzt.xAxis.data = val.dateSet
        optionXjyzt.legend.data = val.typeSet
        const arr = Object.keys(val.typeValueListMap)
        arr.forEach((item, index) => {
          if (item === '年度总收入') {
            optionXjyzt.series.push({
              name: item,
              type: 'line',
              areaStyle: {},
              yAxisIndex: 1,
              data: val.typeValueListMap[item]
            })
          } else {
            optionXjyzt.series.push({
              name: item,
              type: 'bar',
              barMaxWidth: 20,
              yAxisIndex: 0,
              data: val.typeValueListMap[item]
            })
          }
        })
        optionXjyzt.isShow = true
      })
      getSingleValue({
        groupCode: 'ZZYGK'
      }).then((res) => {
        res.body.names.shift()
        this.tortadiagram.title[0].text = formatNumber(res.body.values.shift())  //<span style='padding-top:6px'>亩</span>
        this.tortadiagram.legend.data = res.body.names
        this.tortadiagram.series[0].data = []
        // eslint-disable-next-line no-undef
        var i = 0
        var series = []
        for (i = 0; i < res.body.names.length; i++) {
          var item = {
            name: res.body.names[i],
            value: res.body.values[i]
          }
          series.push(item)
        }
        this.tortadiagram.series[0].data = series
        this.tortadiagram.isShow = true
        this.toLink(this, 'ncpzz', (params) => {
          if (params.name === '主要农产品播种面') {
            this.$router.push({ name: 'Fourstage', query: { code: '000201', name: this.$route.matched[0].name, typeCode: '主要农产品播种面积' }})
          }
        })
      })
      // 农产品产量
      twoPieChartValue({
        groupCode: 'NCPCL'
      }).then((res) => {
        this.pies.legend.data = res.body.names
        this.pies.series[0].data = res.body.values.out
        this.pies.series[1].data = res.body.values.inner
        this.pies.isShow = true
        this.toLink(this, 'ncpcl', (params) => {
          if (params.name === '主要农作物产量') {
            this.$router.push({ name: 'Fourstage', query: { code: '000201', name: this.$route.matched[0].name, typeCode: '主要农作物产量' }})
          }
        })
      })
    },
    async initAMap() {
      try {
        const self = this
        this.amap = await AMap()
        var opts = {
          subdistrict: 0,
          extensions: 'all',
          level: 'city'
        }

        var district = new self.amap.DistrictSearch(opts)
        district.search('咸阳市', function(status, result) {
          var bounds = result.districtList[0].boundaries
          var mask = []
          for (var i = 0; i < bounds.length; i += 1) {
            mask.push([bounds[i]])
          }
          self.map = new self.amap.Map('container', {
            mask: mask,
            center: [108.207004, 34.236131],
            disableSocket: true,
            viewMode: '3D',
            showLabel: false,
            labelzIndex: 130, // 地图标注显示顺序，大于110即可将底图上的默认标注显示在覆盖物（圆、折线、面）之上。
            pitch: 40, // 俯仰角度，默认0，[0,83]，2D地图下无效 。（自V1.4.0开始支持）
            zoom: 16,
            layers: [
              new self.amap.TileLayer.RoadNet({
                // rejectMapMask:true
              }),
              new self.amap.TileLayer.Satellite()
            ]
          })
          // 添加自定义图层
          self.map.plugin(['AMap.CustomLayer'], function() {
            var size = self.map.getSize()
            var canvas = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
            canvas.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
            canvas.setAttribute('width', size.width)
            canvas.setAttribute('height', size.height)

            self.path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
            self.path.onclick = function() {
              // console.log('svg path clicked')
            }
            var styleText = []
            styleText.push('stroke:#132235')
            styleText.push('fill:#132235')
            styleText.push('fill-opacity:0.6')
            self.path.style.cssText = styleText.join(';')

            canvas.appendChild(self.path)
            var customLayer = new self.amap.CustomLayer(canvas, {
              // zooms: [3, 8],
              alwaysRender: true,
              zIndex: 100
            })
            customLayer.render = self.onRender
            self.map.add(customLayer)
          })

          // 添加高度面
          var object3Dlayer = new self.amap.Object3DLayer({ zIndex: 1 })
          self.map.add(object3Dlayer)
          var height = -8000
          var color = '#0088ffcc' // rgba
          var wall = new self.amap.Object3D.Wall({
            path: bounds,
            height: height,
            color: color
          })
          wall.transparent = true
          object3Dlayer.add(wall)

          // 添加描边
          for (let i = 0; i < bounds.length; i += 1) {
            new self.amap.Polyline({
              path: bounds[i],
              strokeColor: '#99ffff',
              strokeWeight: 4,
              map: self.map
            })
          }
          self.plantAreaCrops()
        })
      } catch (err) {
        console.error(err)
      }
    },
    buildPath() {
      var path = []
      var center = this.map.lngLatToContainer(this.starCenter)
      for (let k = 0; k < 6; k += 1) {
        var ag = ((Math.PI * 60) / 180) * k
        var x = center.x + Math.cos(ag) * 500000
        var y = center.y + Math.sin(ag) * 500000
        path.push((k === 0 ? 'M' : 'L') + x + ' ' + y)
      }
      return path.join(' ') + ' Z'
    },
    onRender() {
      var newPath = this.buildPath()
      this.path.setAttribute('d', newPath)
    },
    businessEntity() {
      const p1 = new Promise((resolve, reject) => {
        const map = new this.amap.Map('businessEntity', {
          amapizeEnable: true, // 是否监控地图容器尺寸变化
          zoom: 14, // 初始化地图层级
          mapStyle: 'amap://styles/fa9f091b73ec8e37b8b84784a4791559', // 地图样式
          center: [108.083497, 34.294149] // 初始化地图中心点
        })
        resolve(map)
      })

      const p2 = new Promise((resolve, reject) => {
        produceBusiness().then((res) => {
          resolve(res.body.data)
        })
      })

      Promise.all([p1, p2])
        .then((result) => {
          const self = this
          this.businessEntityMap = result[0]
          // 添加点
          result[1].map((item) => {
            const coordinate = JSON.parse(item.coordinate)
            let url = ''
            this.imgList.map((d) => {
              if (d.type === item.type) {
                url = d.url
              }
            })
            const marker = new this.amap.Marker({
              map: self.businessEntityMap,
              icon: url,
              position: [coordinate.lng, coordinate.lat]
            })
            self.mapData.push({
              position: [coordinate.lng, coordinate.lat],
              data: item
            })
            marker.on('click', function(e) {
              self.produceBusinessInfo(e, item)
            })
          })
          self.setMapCenter()
        })
        .catch((error) => {
          // console.log(error)
        })
    },
    setMapCenter() {
      const self = this
      this.time = setTimeout(() => {
        self.businessEntityMap.setCenter(self.mapData[self.showIndex].position)
        const lnglat = self.mapData[self.showIndex].position
        self.produceBusinessInfo({ lnglat }, self.mapData[self.showIndex].data)
        if (self.showIndex === self.mapData.length - 1) {
          self.showIndex = 0
        } else {
          self.showIndex++
        }
        self.setMapCenter()
      }, 8000)
    },
    drawLoca(data) {
      var layer = new Loca.HeatmapLayer({
        map: this.heatMap
      })
      var list = []
      data.map((item) => {
        const coordinate = JSON.parse(item.coordinate)
        list.push({
          coordinate: [coordinate.lng, coordinate.lat],
          count: item.count
        })
      })
      layer.setData(list, {
        lnglat: 'coordinate',
        value: 'count'
      })

      layer.setOptions({
        style: {
          radius: 16,
          color: {
            0.5: '#2c7bb6',
            0.65: '#abd9e9',
            0.7: '#ffffbf',
            0.9: '#fde468',
            1.0: '#d7191c'
          }
        }
      })

      layer.render()
    },
    // 农产品种植地图
    farming() {
      this.initAMap()
    },
    getHeatMap() {
      const self = this
      const loca = document.createElement('script')
      loca.setAttribute('src', 'http://webapi.amap.com/loca?v=1.3.2&key=52a208e99a6c24ab60208167d15cb5db')
      document.head.appendChild(loca)
      loca.onload = function() {
        // self.heatMap = new self.amap.Map('heatMap', {
        //   mapStyle: 'amap://styles/fa9f091b73ec8e37b8b84784a4791559', // 地图样式
        //   center: [108.207004, 34.236131],
        //   zoom: 14
        // })

        self.heatMap = new self.amap.Map('heatMap', {
          mapStyle: 'amap://styles/fa9f091b73ec8e37b8b84784a4791559', // 地图样式
          zoom: 14,
          center: [108.207004, 34.236131],
          viewMode: '3D'
        })
        self.disasterArea()
      }
    },
    disasterArea() {
      const self = this
      disasterArea().then((res) => {
        const data = res.body.data
        var layer = new Loca.RoundPointLayer({
          map: self.heatMap,
          fitView: true
        })
        const b = []
        data.map((item, index) => {
          const o = JSON.parse(item.coordinate)
          o.mag = item.count / 10
          o.depth = 10
          o.title = '123'
          o.time = +new Date()
          o.lnglat = [o.lng, o.lat].join(',')
          b.push(o)
        })
        layer.setData(b, {
          lnglat: 'lnglat'
        })
        layer.setOptions({
          style: {
            radius: {
              key: 'mag', // 映射字段
              scale: 'linear', // 比例尺
              value: [10, 50], // 输出范围
              input: [4, 8] // 输入范围
            },
            color: this.colorList[0].color,
            opacity: 0.8,
            borderWidth: 1,
            borderColor: this.colorList[0].color
          }
        })

        layer.render()
        // this.drawLoca(res.body.data)
      })
    },
    addPolygon(data) {
      const self = this
      const markers = []
      data.forEach((item, index) => {
        const b = []
        const f = JSON.parse(item.coordinate)
        f.map((ite) => {
          b.push(new this.amap.LngLat(ite.lng, ite.lat))
        })
        let color = ''
        this.colorList.map((d) => {
          if (d.type === item.type) {
            color = d.color
          }
        })
        const polygon = new this.amap.Polygon({
          title: item.name,
          data: item,
          path: b,
          strokeColor: color, // 线颜色
          strokeOpacity: 0.2, // 线透明度
          strokeWeight: 10, // 线宽
          fillColor: color, // 填充色
          fillOpacity: 0.8 // 填充透明度
        })
        // polygon.on('click', function(e) {
        //   self.openInfo(e, item)
        // })
        markers.push(polygon)
      })
      const overlayGroups = new this.amap.OverlayGroup(markers)
      this.map.add(overlayGroups)
    },
    createInfoWindow(title, content) {
      const info = document.createElement('div')
      info.className = 'custom-info input-card content-window-card'
      // 可以通过下面的方式修改自定义窗体的宽高
      // info.style.width = "400px";
      // 定义顶部标题
      const top = document.createElement('div')
      const titleD = document.createElement('div')
      const closeX = document.createElement('div')
      top.className = 'info-top info-top-two'
      titleD.innerHTML = title
      closeX.innerHTML = 'X'
      closeX.className = 'close'
      closeX.onclick = this.closeInfoWindow
      top.appendChild(titleD)
      top.appendChild(closeX)
      info.appendChild(top)

      // 定义中部内容
      const middle = document.createElement('div')
      middle.className = 'info-middle info-middle-two'
      middle.innerHTML = content
      info.appendChild(middle)

      // 定义底部内容
      const bottom = document.createElement('div')
      bottom.className = 'info-bottom'
      bottom.style.position = 'relative'
      bottom.style.top = '0px'
      bottom.style.margin = '0 auto'
      const sharp = document.createElement('img')
      sharp.src = require('@/assets/img/map/up2.png')
      bottom.appendChild(sharp)
      info.appendChild(bottom)
      return info
    },
    produceBusinessInfo(e, data) {
      this.mapType = 'businessEntityMap'
      const self = this
      const title = '详情'
      const content = []
      content.push('<div class="flex"><div class="w-80">名称:</div><div>' + data.name + '</div></div>')
      content.push('<div class="flex"><div class="w-80">地址:</div><div>' + data.address + '</div></div>')
      content.push('<div class="flex"><div class="w-80">类型:</div><div>' + data.type + '</div></div>')
      content.push('<div class="flex"><div class="w-80">联系人:</div><div>' + data.chargePerson + '</div></div>')
      content.push('<div class="flex"><div class="w-80">联系电话:</div><div>' + data.contactNumber + '</div></div>')
      this.infoWindow = new this.amap.InfoWindow({
        isCustom: true, // 使用自定义窗体
        content: self.createInfoWindow(title, content.join('<br/>')),
        offset: new this.amap.Pixel(16, -45)
      })
      this.infoWindow.open(self.businessEntityMap, e.lnglat)
    },
    openInfo(e, item) {
      const self = this
      const title = item.year
      const content = []
      content.push('<div id="mapEcharts"></div>')
      this.infoWindow = new this.amap.InfoWindow({
        isCustom: true, // 使用自定义窗体
        content: self.createInfoWindow(title, content.join('<br/>')),
        offset: new this.amap.Pixel(16, -45)
      })
      this.infoWindow.open(this.map, e.lnglat)

      setTimeout(() => {
        echarts.registerTheme('themes', theme)
        var myChart = echarts.init(document.getElementById('mapEcharts'), 'themes')
        var option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 10,
            data: ['农作物总播种面积', '粮食作物播种面积', '主要农产品播种面积']
          },
          series: [
            {
              name: '访问来源',
              type: 'pie',
              radius: ['30%', '45%'],
              avoidLabelOverlap: false,
              emphasis: {
                label: {
                  show: false,
                  fontSize: '16',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: [
                { value: item.cropsArea, name: '农作物总播种面积' },
                { value: item.foodstuffArea, name: '粮食作物播种面积' },
                { value: item.productsArea, name: '主要农产品播种面积' }
              ]
            }
          ]
        }

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option)
      }, 100)
    },
    closeInfoWindow() {
      if (this.mapType === 'businessEntityMap') {
        this.businessEntityMap.clearInfoWindow()
      } else {
        this.map.clearInfoWindow()
      }
    },
    plantAreaCrops(item) {
      plantAreaCrops().then((res) => {
        this.addPolygon(res.body.data)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.h-33 {
  height: 32%;
}
div[data-bottom] {
  background: url(~@/assets/img/gradients-right.png) no-repeat;
  background-size: 100% 100% !important;
}
.h-24 {
  height: 23.2%;
}
.map-box {
  position: relative;
}

.map-type {
  position: absolute;
  top: 28px;
  right: 28px;
  z-index: 1000;
}
.item-map-type {
  cursor: pointer;
  width: 120px;
  height: 36px;
  background: rgba(36, 193, 247, 0.4);
  border: 1px solid rgba(26, 116, 207, 1);
  color: #ffffff;
  text-align: center;
  line-height: 36px;
  margin-bottom: 16px;
  font-size: 14px;
}
.active {
  background: #24c1f7;
  opacity: 1;
}
.map-legend {
  padding: 12px 18px;
  position: absolute;
  left: 20px;
  bottom: 20px;
  z-index: 1000;
  color: #fff;
  border: solid 1px #5c6d7c;
  background: rgba(18, 33, 53, 0.8);
  border-radius: 4px;
}
.map-legend-color {
  width: 34px;
  height: 37px;
  margin-right: 10px;
  margin-top: -10px;
}
.map-legend-color img {
  width: 100%;
  height: 100%;
}
.map-legend-item {
  margin-bottom: 8px;
}
.map-legend-item:last-child {
  margin-bottom: 0;
}

.map-legend-bar {
  padding: 12px 18px;
  position: absolute;
  left: 20px;
  bottom: 20px;
  z-index: 1000;
  color: #fff;
  background: rgba(18, 33, 53, 0.8);
  border: solid 1px #5c6d7c;
  border-radius: 4px;
}
.map-legend-bar-color {
  width: 40px;
  height: 18px;
  margin-right: 10px;
}
.map-legend-bar-item {
  margin-bottom: 8px;
}
.map-legend-bar-item:last-child {
  margin-bottom: 0;
}
</style>
